package com.seek.service.imp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.seek.authcheck.constants.AuthConstant;
import com.seek.authcheck.constants.AuthProductEnum;
import com.seek.authcheck.constants.CarrierConstant;
import com.seek.authcheck.constants.NoticeConstant;
import com.seek.cache.CacheUtil;
import com.seek.constants.ApiParamsConstant;
import com.seek.constants.RedisCustomerConstant;
import com.seek.model.authcheck.CarrierAuthModel;
import com.seek.model.authcheck.CarrierCallModel;
import com.seek.model.entity.TAuthMetric;
import com.seek.model.entity.TBizFlow;
import com.seek.model.entity.TCustomer;
import com.seek.model.entity.TCustomerAddrbook;
import com.seek.model.entity.TCustomerMetric;
import com.seek.model.entity.TCustomerMobileBill;
import com.seek.model.entity.TCustomerMobileInfo;
import com.seek.service.AuthMetricService;
import com.seek.service.BaseAuthCheckService;
import com.seek.service.CustomerAddrbookService;
import com.seek.service.CustomerMetricService;
import com.seek.service.CustomerMobileBillService;
import com.seek.service.CustomerMobileInfoService;
import com.seek.service.CustomerService;
import com.seek.service.BizFlowService;
import com.seek.util.CommonUtil;
import com.seek.util.DateUtil;
import com.seek.util.MD5Util;
import com.seek.util.Push2SingleUtil;
import com.seek.util.UpOtherImgToUpyun;
import com.seek.util.authcheck.AuthCheckUtils;
import com.seek.util.authcheck.CollectUtils;
import com.sinovatech.common.config.GlobalConfig;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by weh on 2017/7/2.
 */
@Service(value = "carrierAuthCheck")
public class CarrierAuthCheckImpl implements BaseAuthCheckService {

  private static final Logger logger = LoggerFactory.getLogger(CarrierAuthCheckImpl.class);

  @Resource
  private BizFlowService bizFlowService;

  @Resource
  private CustomerService customerService;

  @Resource
  private CustomerMobileInfoService customerMobileInfoService;

  @Resource
  private CustomerMetricService customerMetricService;

  @Resource
  private CustomerAddrbookService customerAddrbookService;

  @Resource
  private AuthMetricService authMetricService;

  @Resource
  private CustomerMobileBillService customerMobileBillService;

  @Resource
  private Push2SingleUtil push2SingleUtil;

  @Override
  @Transactional
  public void autoCheck(JSONObject json) {
    String bizNo = "";
    try {
      String orgBizNo = json.getString(NoticeConstant.TASK_ID);

      //查询流水
      Map<String, Object> queryMap = new HashMap<>();
      queryMap.put("orgBizNo", orgBizNo);
      queryMap.put("deleted", 0);
      List<TBizFlow> bizFlows = bizFlowService.getBizFlowByParams(queryMap);
      if (CollectionUtils.isEmpty(bizFlows) || bizFlows.size() != 1) {
        logger.error("没有查询到taskId:{}的数据", orgBizNo);
        //没有查询到流水,缓存到redis,防止回调发生在更新taskId之前
        CacheUtil.putRedisDataEx(RedisCustomerConstant.TASK_KEY_PREFIX + orgBizNo,
            JSON.toJSONString(json), ApiParamsConstant.REDIS_EXPIRE_TIME);
        return;
      }

      TBizFlow bizFlow = bizFlows.get(0);
      String flowStatus = bizFlow.getStatus();
      int deleted = bizFlow.getDeleted();
      if (deleted == 1) {
        logger.warn("查询到流水号{}已失效", bizNo);
        bizFlowService.updateBizFlow(
            "update t_biz_flow set status = ? ,modify_time= now() where biz_no = ?",
            new Object[]{1, bizNo});
        return;
      }
      if (StringUtils.isNotEmpty(flowStatus) && StringUtils.equals(flowStatus, "1")) {
        logger.warn("查询到流水号{}已经调用成功，无需再次处理", bizNo);
        return;
      }
      //更新流水
      logger.info("更新流水,{}", bizNo);
      String updateBizFlowSql = "update t_biz_flow set status = ? ,modify_time= now() where biz_no = ? and deleted = ?";
      bizFlowService.updateBizFlow(updateBizFlowSql, new Object[]{"1", bizFlow.getBizNo(), 0});
      //查询客户基本信息
      String queryCustSql = "select * from t_customer where id = ? and company_id = ?";
      List<TCustomer> custs = customerService.findBySql(queryCustSql,
          new Object[]{bizFlow.getCustomerId(), bizFlow.getCompanyId()});
      if (CollectionUtils.isEmpty(custs) || custs.size() != 1) {
        logger.error("没有查询到客户号为{}的客户信息", bizFlow.getCustomerId());
        return;
      }
      TCustomer customer = custs.get(0);
      JSONObject jsonObject = new JSONObject();
      jsonObject.put(NoticeConstant.API_KEY,
          GlobalConfig.getProperty(NoticeConstant.PROP_NAME, NoticeConstant.PUB_KEY));
      jsonObject.put(NoticeConstant.PRODUCT_CODE, AuthProductEnum.CARRIER.getProductCode());
      jsonObject.put(NoticeConstant.TASK_ID, json.getString(NoticeConstant.TASK_ID));
      String requestJson = JSON.toJSONString(jsonObject);
      String signText = requestJson + "|" + GlobalConfig
          .getProperty(NoticeConstant.PROP_NAME, NoticeConstant.SECURITY_KEY);
      String sign = MD5Util.MD5(signText);
      String url =
          GlobalConfig.getProperty(NoticeConstant.PROP_NAME, NoticeConstant.YOUDU_DATA_URL)
              + sign;
      logger.info("获取运营商数据,url:{},data:{},taskId:{}", url, requestJson,json.getString(NoticeConstant.TASK_ID));
      Date start = new Date();
      String dataResponse = CollectUtils.getDataResponse(url, requestJson, 0);
//      logger.info("获取的数据为:{}", dataResponse);
      if (StringUtils.isEmpty(dataResponse)) {
        logger.error("获取数据出错");
        return;
      }
      logger.info("获取运营商报文耗时;{},taskId:{}", new Date().getTime() - start.getTime(),json.getString(NoticeConstant.TASK_ID));
      JSONObject respJson = (JSONObject) JSON.parse(dataResponse);
      // upload json
      String fileUrl = UpOtherImgToUpyun.writeFile(bizFlow.getCustomerId() + "_carrier.json",
          dataResponse.getBytes("UTF-8"));
      //获取规则
//      logger.info("获取规则");
      Map<String, Object> paramsMap = new HashMap<>();
      paramsMap.put("authProduct", AuthProductEnum.CARRIER.getProductCode().toUpperCase());
      paramsMap.put("companyId", bizFlow.getCompanyId());
      List<TAuthMetric> authMetrics = authMetricService.queryAuthMetricBySql(paramsMap);
//      logger.info("获取规则结果:{}", JSON.toJSONString(authMetrics));
//      logger.info("创建认证模型");
      CarrierAuthModel carrierAuthModel = new CarrierAuthModel();
      JSONObject data = respJson.getJSONObject("data");

      String addressSql = "select id,phone_no as phoneNo,phone_name as phoneName,"
          + "ifnull(calls_number,0) as callsNumber from t_customer_addrbook "
          + "where company_id = ? and customer_id = ?";
      List<Map<String, Object>> addressBooks = customerAddrbookService
          .findMapBySql(addressSql, new Object[]{bizFlow.getCompanyId(), bizFlow.getCustomerId()});
      Map<String, TCustomerAddrbook> contactMap = new HashMap<>();
//      logger.info("获取通讯录,{}", JSON.toJSONString(addressBooks));
      if (CollectionUtils.isNotEmpty(addressBooks)) {
        carrierAuthModel.setPhoneCount(addressBooks.size() + "");
        for (Map<String, Object> addressBook : addressBooks) {
          TCustomerAddrbook customerAddrbook = new TCustomerAddrbook();
          customerAddrbook.setId(CommonUtil.getLongValue(addressBook.get("id")));
          customerAddrbook.setPhoneNo(String.valueOf(addressBook.get("phoneNo")));
          customerAddrbook.setPhoneName(String.valueOf(addressBook.get("phoneName")));
          customerAddrbook.setCallsNumber(CommonUtil.getIntValue(addressBook.get("callsNumber")));
          contactMap.put(customerAddrbook.getPhoneNo(), customerAddrbook);
        }
      } else {
        carrierAuthModel.setPhoneCount("0");
      }

      createCarrierAuthModel(carrierAuthModel, data, contactMap);
      logger.info("认证模型数据,{}", JSON.toJSONString(carrierAuthModel));
//      logger.info("开始认证....");
      List<TAuthMetric> carrierAuthResult = getCarrierAuthResult(carrierAuthModel, authMetrics);
//      logger.info("认证结果,{}", JSON.toJSONString(carrierAuthResult));
      //删除历史采集数据(运营商基本信息)
      String delSql = "delete from t_customer_mobile_info where company_id = ? and customer_id = ?";
      customerMobileInfoService
          .executeUpdate(delSql, new Object[]{bizFlow.getCompanyId(), bizFlow.getCustomerId()});

      TCustomerMobileInfo mobileInfo = new TCustomerMobileInfo();
      mobileInfo.setCompanyId(bizFlow.getCompanyId());
      mobileInfo.setCustomerId(bizFlow.getCustomerId());
      mobileInfo.setLastModifyTime(new Date());
      mobileInfo.setFilePath(fileUrl);
      createMobileInfo(mobileInfo, data);

      //删除历史采集数据(账单)
      String delBillSql = "delete from t_customer_mobile_bill where company_id = ? and customer_id = ?";
      customerMobileInfoService
          .executeUpdate(delBillSql, new Object[]{bizFlow.getCompanyId(), bizFlow.getCustomerId()});

      List<TCustomerMobileBill> mobileBills = new ArrayList<>();
      createMobileBill(mobileBills, data, bizFlow);
//      logger.info("插入客户账单数据,{}", JSON.toJSONString(mobileBills));
      //插入采集数据(客户运营商账单信息)
      customerMobileBillService.saveBatch(mobileBills);

      logger.info("认证结果:{}", JSON.toJSONString(carrierAuthModel));
      logger.info("更新认证状态");
      int status =
          checkModel(carrierAuthModel) ? AuthConstant.AUTH_SUCCESS : AuthConstant.AUTH_FAIL;
      customer.setMobileStatus(status);
      //update 客户信息表 审核状态
      customerService.update(customer);
      String sql = "update t_customer_metric set deleted = ?,modify_time = ?  where company_id = ? and customer_id = ? and deleted = ? ";
      customerMetricService.executeUpdate(sql,
          new Object[]{1, new Date(), bizFlow.getCompanyId(), bizFlow.getCustomerId(), 0});
      List<TCustomerMetric> customerMetrics = new ArrayList<>();
      for (TAuthMetric metric : carrierAuthResult) {
        TCustomerMetric customerMetric = createCustomerMetric(metric);
        customerMetric.setCustomerId(bizFlow.getCustomerId());
        customerMetric.setCompanyId(bizFlow.getCompanyId());
        customerMetrics.add(customerMetric);
      }
      //insert customer_metric
//      logger.info("插入认证指标数据,{}", JSON.toJSONString(customerMetrics));
      customerMetricService.saveBatch(customerMetrics);
      Map<String, Object> cacheData = new HashMap<>();
      if (status == AuthConstant.AUTH_SUCCESS) {
        mobileInfo.setAuditStatus(1);
        push2SingleUtil.push2Single(Push2SingleUtil.TYPE_OF_MOBILE_SUC, customer.getClientId());
      } else {
        mobileInfo.setAuditStatus(2);
        mobileInfo.setAuditRemark(carrierAuthModel.getCheckMsg());
        push2SingleUtil
            .push2Single(Push2SingleUtil.TYPE_OF_MOBILE_FAIL, customer.getClientId());
      }

//      logger.info("插入运营商基本信息数据,{}", JSON.toJSONString(mobileInfo));
      //插入采集数据(客户运营商基本信息)
      customerMobileInfoService.save(mobileInfo);
//      logger.info("更新通讯录通话次数数据,{}", JSON.toJSONString(contactMap));
      customerAddrbookService.updateCallCountsBatch(contactMap);

      cacheData.put(RedisCustomerConstant.CARRIER_STATUS, status);
      String token = CacheUtil
          .getRedisData(RedisCustomerConstant.CUST_KEY_PREFIX + bizFlow.getCustomerId());
      if (StringUtils.isNotEmpty(token)) {
        CacheUtil.refreshCustRedis(token, cacheData);
      }
    } catch (Exception e) {
      e.printStackTrace();
      logger.error("运营商自动认证出错, 错误信息:{}", e.getMessage());
    }

  }

  public static String getMD5Sign(String pub_key, String partner_order_id, String sign_time,
      String security_key) throws Exception {
    String signStr = String
        .format("pub_key=%s|partner_order_id=%s|sign_time=%s|security_key=%s", pub_key,
            partner_order_id, sign_time, security_key);
    logger.info("signField：" + signStr + GlobalConfig
        .getProperty(NoticeConstant.PROP_NAME, NoticeConstant.SECURITY_KEY));
    return MD5Util.MD5(signStr);
  }


  private static boolean checkModel(CarrierAuthModel carrierAuthModel) {

    return carrierAuthModel.isAgeCheck() && carrierAuthModel.isOutServiceCheck() && carrierAuthModel
        .isCallMatchesCheck();
//    return carrierAuthModel.isAgeCheck() && carrierAuthModel.isOutServiceCheck();
  }


  /**
   * 获取客户运营商账单
   **/
  private static void createMobileBill(List<TCustomerMobileBill> list, JSONObject data,
      TBizFlow bizFlow) {

    try {
      JSONArray bills = data.getJSONArray(CarrierConstant.BILLS);

      if (CollectionUtils.isNotEmpty(bills)) {
        for (int i = 0; i < bills.size(); i++) {
          JSONObject billJson = (JSONObject) bills.get(i);
          TCustomerMobileBill customerMobileBill = new TCustomerMobileBill();
          long amount = new BigDecimal(billJson.getString(CarrierConstant.BILL_FEE)).longValue();
          String billMonth = billJson.getString(CarrierConstant.BILL_MONTH);
          customerMobileBill.setBillAmount(amount);
          customerMobileBill.setBillMonth(billMonth);
          customerMobileBill.setDeleted(0);
          customerMobileBill.setCompanyId(bizFlow.getCompanyId());
          customerMobileBill.setCustomerId(bizFlow.getCustomerId());
          list.add(customerMobileBill);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      logger.error("获取账单明细失败,错误信息为:{},数据为:{}", e.getMessage(), JSON.toJSONString(data));
    }
  }


  /**
   * 创建客户指标
   */
  private TCustomerMetric createCustomerMetric(TAuthMetric authMetric) {
    TCustomerMetric customerMetric = new TCustomerMetric();
    customerMetric.setAuthRuleId(authMetric.getAuthRuleId());
    customerMetric.setCreateTime(new Date());
    customerMetric.setModifyTime(customerMetric.getCreateTime());
    customerMetric.setDeleted(0);
    customerMetric.setMetricDesc(authMetric.getDesc());
    customerMetric.setScore(authMetric.getAuthValue());
    customerMetric.setMetricValue(authMetric.getValue());

    return customerMetric;
  }


  /**
   * 获取客户运营商基本资料
   */
  private static void createMobileInfo(TCustomerMobileInfo customerMobileInfo,
      JSONObject data) {
    Integer collectCode = CommonUtil.getIntValue(data.getString(CarrierConstant.COLLECT_CODE));

    customerMobileInfo.setCode(null != collectCode ? collectCode : 9);
    customerMobileInfo.setMessage(data.getString(CarrierConstant.COLLECT_MSG));
    customerMobileInfo.setName(data.getString(CarrierConstant.NAME));
    String idCard = data.getString(CarrierConstant.ID_CARD);
    customerMobileInfo.setIdcard(data.getString(
        StringUtils.isEmpty(idCard) || StringUtils.equalsIgnoreCase(idCard, "null") ? "" : idCard));
    customerMobileInfo.setCarrier(data.getString(CarrierConstant.CARRIER));
    customerMobileInfo.setProvince(data.getString(CarrierConstant.PROVINCE));
    customerMobileInfo.setCity(data.getString(CarrierConstant.CITY));
    customerMobileInfo.setPhoneNo(data.getString(CarrierConstant.MOBILE));
//    logger.info("运营商手机号:{}",customerMobileInfo.getPhoneNo());

    String openTime = data.getString(CarrierConstant.OPEN_TIME);
    Date dateOpenTime = null;
    if (StringUtils.isNotEmpty(openTime) && (!StringUtils.equalsIgnoreCase(openTime, "null"))) {
      dateOpenTime = DateUtil.getDateByStrings(openTime);
    }
    customerMobileInfo.setOpenTime(dateOpenTime);
    customerMobileInfo.setLevel(data.getString(CarrierConstant.LEVEL));
    String packageName = data.getString(CarrierConstant.PACKAGE_NAME);
    customerMobileInfo.setPackageName(
        StringUtils.isEmpty(packageName) || StringUtils.equalsIgnoreCase(packageName, "null") ? ""
            : packageName);
    String state = data.getString(CarrierConstant.STATE);
    customerMobileInfo.setState(
        StringUtils.isEmpty(state) || StringUtils.equalsIgnoreCase(state, "null") ? "-1" : state);
    Integer balance = CommonUtil.getIntValue(data.getString(CarrierConstant.CUR_BALANCE));
    customerMobileInfo.setAvailableBalance(null != balance ? balance : null);

  }

  /**
   * 创建运营商证认证模型
   */
  private static void createCarrierAuthModel(CarrierAuthModel carrierAuthModel,
      JSONObject data, Map<String, TCustomerAddrbook> contactMap) {
    String openTime = data.getString(CarrierConstant.OPEN_TIME);

    if (StringUtils.isNotEmpty(openTime) && (!StringUtils.equalsIgnoreCase(openTime, "null"))) {
      setAge(carrierAuthModel, openTime);
    }
    JSONArray calls = data.getJSONArray(CarrierConstant.CALLS);
    if (CollectionUtils.isNotEmpty(calls)) {
      setCallProps(carrierAuthModel, calls, contactMap);
    }
    JSONArray bills = data.getJSONArray(CarrierConstant.BILLS);

    if (CollectionUtils.isNotEmpty(bills)) {
      setAvgAmount(carrierAuthModel, bills);
    }
  }

  /**
   * 设置入网网龄
   */
  private static void setAge(CarrierAuthModel carrierAuthModel, String openTime) {
    try {
      Date startDate = DateUtil.getDateByStrings(openTime);
      Calendar calBegin = Calendar.getInstance(); //获取日历实例
      Calendar calEnd = Calendar.getInstance();
      calBegin.setTime(startDate); //字符串按照指定格式转化为日期
      calEnd.setTime(new Date());
      int year = calEnd.get(Calendar.YEAR) - calBegin.get(Calendar.YEAR);
      int month = calEnd.get(Calendar.MONTH) - calBegin.get(Calendar.MONTH);
      int age = year * 12 + month;
      carrierAuthModel.setAge(String.valueOf(age));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * 设置平均月账单
   */
  private static void setAvgAmount(CarrierAuthModel carrierAuthModel, JSONArray bills) {
    Double totalBillAmount = new Double(0);
    try {
      for (int i = 0; i < bills.size(); i++) {
        JSONObject billJson = (JSONObject) bills.get(i);
        totalBillAmount += Double.parseDouble(billJson.getString(CarrierConstant.BILL_FEE));
      }
      DecimalFormat decimalFormat = new DecimalFormat("0");
      double avgAmount = totalBillAmount / bills.size();
      carrierAuthModel.setBillAmount(decimalFormat.format(avgAmount));

    } catch (Exception e) {
      e.printStackTrace();
      logger.error("获取平均月账单失败,错误信息为:{},数据为:{}", e.getMessage(), JSON.toJSONString(bills));
    }
  }

  /**
   * 设置通话参数
   */
  private static void setCallProps(CarrierAuthModel carrierAuthModel, JSONArray calls,
      Map<String, TCustomerAddrbook> contactMap) {
    String reg = "^爸*$|^妈*$|^姐*$|^舅*$|^叔*$|^丈*$|^父*$|^母*$";
    Pattern pattern = Pattern.compile(reg);
    Date monthBefore = get2MonthBefore();

    int matchVIP = 0;//匹配联系人个数
    Set<String> matchSet = new HashSet<>();//匹配到的通讯录联系人
    int outServiceCount = 0;//停机次数

    int callCount = 0;//通话次数
    try {
      List<CarrierCallModel> callModels = new ArrayList<>();

      for (int i = 0; i < calls.size(); i++) {
        JSONObject callJson = calls.getJSONObject(i);
        String billMonth = callJson.getString(CarrierConstant.BILL_MONTH);

        if (StringUtils.isNotEmpty(billMonth)) {
          Date month = DateUtil.getDateByString(billMonth + "-01", DateUtil.DATE_FORMAT_YMD);

          callCount += Integer.valueOf(callJson.getString(CarrierConstant.CALL_TOTAL_SIZE));
          JSONArray callItmes = callJson.getJSONArray(CarrierConstant.CALL_ITMES);
          for (int j = 0; j < callItmes.size(); j++) {
            JSONObject callItem = callItmes.getJSONObject(j);
            String phoneNumber = callItem.getString(CarrierConstant.PEER_NUMBER);

            String time = callItem.getString(CarrierConstant.CALL_TIME);
            if (StringUtils.isNotEmpty(time)) {
              CarrierCallModel callModel = new CarrierCallModel();
              callModel.setPeerNumber(phoneNumber);
              callModel.setTime(new Date());
              callModels.add(callModel);
            }
            if (month.before(monthBefore)) {
              break;
            }
            /**以下操作均是加工2个月内指标**/
            if (contactMap.containsKey(phoneNumber)) {
              matchSet.add(phoneNumber);
              TCustomerAddrbook customerAddrbook = contactMap.get(phoneNumber);
              customerAddrbook.setCallsNumber(customerAddrbook.getCallsNumber() + 1);
              Matcher matcher = pattern.matcher(customerAddrbook.getPhoneName());
              if (matcher.matches()) {
                matchVIP++;
              }
            }
          }
        }
      }
//      logger.info("匹配信息:{}",JSON.toJSONString(matchSet));
//      logger.info("匹配数量:{},通讯录个数:{}",matchSet.size(),contactMap.size());
      if (CollectionUtils.isEmpty(matchSet) || MapUtils.isEmpty(contactMap)) {
        carrierAuthModel.setCallMatches("0");
      } else {
        DecimalFormat decimalFormat = new DecimalFormat("0.00");

        carrierAuthModel
            .setCallMatches(decimalFormat.format(matchSet.size() * 1.00 / contactMap.size()));
      }
      Collections.sort(callModels);

      for (int i = 0; i < callModels.size() - 1; i++) {
        long callInterval =
            callModels.get(i).getTime().getTime() - callModels.get(i + 1).getTime().getTime();
        if (callInterval >= CarrierConstant.CALL_INTERVAL) {
          outServiceCount++;
        }
      }
      carrierAuthModel.setCallCount(String.valueOf(callCount));
      carrierAuthModel.setPhoneCount(String.valueOf(contactMap.size()));
      carrierAuthModel.setOutService(String.valueOf(outServiceCount));
      carrierAuthModel.setSearchKey(String.valueOf(matchVIP));
    } catch (Exception e) {
      e.printStackTrace();
      logger.error("设置通话参数失败,错误信息为:{},数据为:{}", e, JSON.toJSONString(calls));
    }

  }

  /**
   * 获取2个月前1号
   */
  private static Date get2MonthBefore() {
    try {
      Calendar calendar = Calendar.getInstance(); //获取日历实例
      calendar.setTime(new Date());
      calendar.add(Calendar.MONTH, -2);
      calendar.set(Calendar.DATE, 1);
      return DateUtil.getDate(calendar.getTime(), DateUtil.DATE_FORMAT_YMD);
    } catch (Exception e) {
      logger.error("获取2个月前日期失败,{}", e.getMessage());
    }
    return null;
  }

  /**
   * 运营商规则校验
   */
  private List<TAuthMetric> getCarrierAuthResult(CarrierAuthModel model,
      List<TAuthMetric> authMetrics) {
    List<TAuthMetric> result = new ArrayList<>();
    try {
      Map<String, List<TAuthMetric>> ruleMap = new HashMap<>();
      for (TAuthMetric metric : authMetrics) {
        List<TAuthMetric> metrics = null;
        String key = metric.getAuthProduct() + "#" + metric.getAuthDimension();
        if (ruleMap.containsKey(key) && CollectionUtils.isNotEmpty(ruleMap.get(key))) {
          metrics = ruleMap.get(key);
        } else {
          metrics = new ArrayList<>();
        }
        metrics.add(metric);
        ruleMap.put(key, metrics);
      }
      TAuthMetric ageChcekResult = AuthCheckUtils
          .getAuthResult(model, CarrierConstant.AGE, ruleMap);
      TAuthMetric outServiceChcekResult = AuthCheckUtils
          .getAuthResult(model, CarrierConstant.OUT_SERVICE, ruleMap);
      TAuthMetric billAmountChcekResult = AuthCheckUtils
          .getAuthResult(model, CarrierConstant.BILL_AMOUNT, ruleMap);

      TAuthMetric phoneCountChcekResult = AuthCheckUtils
          .getAuthResult(model, CarrierConstant.PHONE_COUNT, ruleMap);

      TAuthMetric callCountChcekResult = AuthCheckUtils
          .getAuthResult(model, CarrierConstant.CALL_COUNT, ruleMap);

      TAuthMetric searchKeyChcekResult = AuthCheckUtils
          .getAuthResult(model, CarrierConstant.SEARCH_KEY, ruleMap);

      TAuthMetric callMatchesChcekResult = AuthCheckUtils
          .getCallMatchesCheck(model, ruleMap);

      result.add(ageChcekResult);
      result.add(outServiceChcekResult);
      result.add(billAmountChcekResult);
      result.add(phoneCountChcekResult);
      result.add(callCountChcekResult);
      result.add(searchKeyChcekResult);
      result.add(callMatchesChcekResult);

      logger.info(JSON.toJSONString(ageChcekResult));
      logger.info(JSON.toJSONString(outServiceChcekResult));
      logger.info(JSON.toJSONString(billAmountChcekResult));
      logger.info(JSON.toJSONString(phoneCountChcekResult));
      logger.info(JSON.toJSONString(callCountChcekResult));
      logger.info(JSON.toJSONString(callMatchesChcekResult));
      if (null != ageChcekResult
          && ageChcekResult.getAuthPass() == AuthConstant.CHECK_SUCCESS) {
        model.setAgeCheck(true);
        logger.info(ageChcekResult.getAuthDesc() + "认证成功！");

      } else {
        model.setAgeCheck(false);
        model.setCheckMsg(ageChcekResult.getFailRemark());
        logger.info(ageChcekResult.getAuthDesc() + "认证失败！");
      }

      if (null != outServiceChcekResult) {
        if (outServiceChcekResult.getAuthPass() == AuthConstant.CHECK_SUCCESS) {
          model.setOutServiceCheck(true);
          logger.info(outServiceChcekResult.getAuthDesc() + "认证成功！");
        } else {
          model.setAgeCheck(false);
          model.setCheckMsg(outServiceChcekResult.getFailRemark());
          logger.info(outServiceChcekResult.getAuthDesc() + "认证失败！");
        }
      }

      if (null != callMatchesChcekResult) {
        if (callMatchesChcekResult.getAuthPass() == AuthConstant.CHECK_SUCCESS) {
          model.setCallMatchesCheck(true);
          logger.info(callMatchesChcekResult.getAuthDesc() + "认证成功！");
        } else {
          model.setCallMatchesCheck(false);
          model.setCheckMsg(callMatchesChcekResult.getFailRemark());
          logger.info(callMatchesChcekResult.getAuthDesc() + "认证失败！");
        }
      } else {
        model.setCallMatchesCheck(false);
        model.setCheckMsg("通话记录和通讯录匹配度规则认证失败！");

      }
      return result;
    } catch (Exception e) {
      e.printStackTrace();
      logger.error("运营商自动认证失败! {}", e.getMessage());
    }

    return null;

  }
}
